import SITE from '@/site.config'
import { NotionAPI } from 'notion-client'
import { idToUuid } from 'notion-utils'
import getAllPageIds from './getAllPageIds'
import getPageProperties from './getPageProperties'
import getPageBlock from "./getPageBlock";
import { defaultMapImageUrl, uuidToId } from "../utils";

export async function getAllPosts() {
  let id = SITE.notionPageId;
  const authToken = SITE.notionAccessToken || null;
  const api = new NotionAPI({ authToken });
  const response = await api.getPage(id);

  id = idToUuid(id);
  const collection = Object.values(response.collection)[0]?.value;
  const collectionQuery = response.collection_query;
  const block = response.block;
  const schema = collection?.schema;
  let tagsColor = [];

  for(const key in schema) {
    if(schema[key].type === "multi_select" && schema[key].name === 'tags') {
      tagsColor = schema[key].options;
    }
  }

  // console.log("tagsColor---", tagsColor);

  const rawMetadata = block[id].value;

  // Check Type
  if (rawMetadata?.type !== "collection_view_page") {
    console.log(`pageId "${id}" is not a database`);
    return null;
  } else {
    // Construct Data
    const pageIds = getAllPageIds(collectionQuery);

    const data = [];
    for (let i = 0; i < pageIds.length; i++) {
      const id = pageIds[i];
      const properties = (await getPageProperties(id, block, schema)) || null;

      // console.log("properties---", properties);

      // Add fullwidth, createdtime to properties
      properties.createdTime = new Date(
        block[id].value?.created_time
      ).toString();
      properties.fullWidth = block[id].value?.format?.page_full_width ?? false;

      const info = await getPageBlock(uuidToId(id));
      properties.cover = info.cover;
      properties.icon = info.icon;

      const tags = properties.tags;
      const colorTags = tags && tags.length > 0 && tagsColor.filter((v) => tags.indexOf(v.value) > -1) || [];
      properties.tags = colorTags;

      data.push(properties);
    }

    // remove all the the items doesn't meet requirements
    const posts = data.filter((post) => {
      return (
        post.title &&
        post.slug &&
        post?.status?.[0] === "Published" &&
        (post?.type?.[0] === "Post" || post?.type?.[0] === "Page")
      );
    });

    // Sort by date
    if (SITE.sortByDate) {
      posts.sort((a, b) => {
        const dateA = new Date(a?.date?.start_date || a.createdTime);
        const dateB = new Date(b?.date?.start_date || b.createdTime);
        return dateB - dateA;
      });
    }
    // console.log('posts---', posts);
    return posts;
  }
}
